﻿using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Windows;

using ABCat.Core;
using ABCat.Core.Plugins;
using ABCat.UI.WPF.Models;

using Xceed.Wpf.AvalonDock.Layout.Serialization;

using UserControl = System.Windows.Controls.UserControl;

namespace ABCat.UI.WPF.UI
{
	public partial class CatalogViewerUc : UserControl
	{
		#region + Fields +

		private ABCatViewModel _abCatModel;
		private Context _context;

		#endregion
		#region + Properties +

		public Context Context
		{
			get { return _context; }
			private set { _context = value; }
		}

		#endregion
		#region + Ctor +

		public CatalogViewerUc()
		{
			InitializeComponent();
		}

		#endregion
		#region + Logic +

		public void Init(Context context)
		{
			Context = context;
			_abCatModel = new ABCatViewModel(context);
			DataContext = _abCatModel;
			FilterUc.FilteringLogicStandard = _abCatModel.Filter;
			StatusBarStateUc.DataContext = _abCatModel.StatusBarStateModel;
		}

		public void RestoreLayouts()
		{
			if (_abCatModel.RecordsListUc != null) _abCatModel.RecordsListUc.RestoreLayout();
			if (_abCatModel.NormalizationSettingsEditorModel.NormalizationSettingsEditorPlugin != null) _abCatModel.NormalizationSettingsEditorModel.NormalizationSettingsEditorPlugin.RestoreLayout();

			//var dockingManagerLayout = ABCatConfig ["CatalogViewerUc.DockingManager"] as byte[];
			byte[] layout;
			if (Config.TryLoadLayout("CatalogViewerUc_DockingManager", out layout))
			{
				using (var memoryStream = new MemoryStream(layout))
				{
					var layoutSerializer = new XmlLayoutSerializer(DockingManager);
					layoutSerializer.Deserialize(memoryStream);
				}
			}
		}

		public void StoreLayouts()
		{
			if (Context == null) return;
			if (_abCatModel != null)
			{
				if (_abCatModel.RecordsListUc != null) _abCatModel.RecordsListUc.StoreLayout();
				if (_abCatModel.NormalizationSettingsEditorModel.NormalizationSettingsEditorPlugin != null) _abCatModel.NormalizationSettingsEditorModel.NormalizationSettingsEditorPlugin.StoreLayout();
			}

			using (var memoryStream = new MemoryStream())
			{
				new XmlLayoutSerializer(DockingManager).Serialize(memoryStream);
				Config.SaveLayout("CatalogViewerUc_DockingManager", memoryStream.ToArray());
			}
		}

		#endregion
	}
}